package gobelinmaker.server;

import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

/**
 * Egyenes-egyenes metszéspontszámítás osztálya.
 * @see <a href="http://blog.persistent.info/2004/03/java-lineline-intersections.html">http://blog.persistent.info/2004/03/java-lineline-intersections.html</a>
 */
public class LineIntersection {
    public static Point2D getLineLineIntersection(
            Line2D l1,
            Line2D l2)
    {
        if (!l1.intersectsLine(l2)) return null;

        double  x1 = l1.getX1(), y1 = l1.getY1(),
                x2 = l1.getX2(), y2 = l1.getY2(),
                x3 = l2.getX1(), y3 = l2.getY1(),
                x4 = l2.getX2(), y4 = l2.getY2();

        double x = det(det(x1, y1, x2, y2), x1 - x2,
                             det(x3, y3, x4, y4), x3 - x4)/
                         det(x1 - x2, y1 - y2, x3 - x4, y3 - y4);
        double y = det(det(x1, y1, x2, y2), y1 - y2,
                             det(x3, y3, x4, y4), y3 - y4)/
                         det(x1 - x2, y1 - y2, x3 - x4, y3 - y4);

        return new Point2D.Double(x, y);
    }

    static double det(double a, double b, double c, double d)
    {
        return a * d - b * c;
    }
}
